package com.qdu.config;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

	//注入要使用的UserDetailsService对象，这里注入的是自定义的CustomUserDetailsService的对象
	@Autowired
	private UserDetailsService userDetailsService;
	
	@Autowired
	AuthenticationSuccessHandler successHandler;
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		//指定验证和授权用户使用的UserDetailsService对象是哪个
		//并且指定使用的密码加密器
		auth.userDetailsService(userDetailsService)
		    .passwordEncoder(passwordEncoder());
	}

	@Override
	public void configure(WebSecurity web) throws Exception {

		web.ignoring().antMatchers("/socket/asset","/static/css/**","/static/js/**","/static/img/**","/static/theme/**","/favicon.ico","/uimg/**");
		//放行一些带此前缀的请求
		web.ignoring().antMatchers("/manager/**","/usert/**","/job/**","/hrt/**","/buss/**");
	//	web.ignoring().antMatchers("/manager/**","/usert/**","/job/**","/hrt/**");
	}
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
		        .antMatchers("/","/index","/login","/login_failed","/usert/**","/authentication/form","/logout").permitAll()
		        .antMatchers("/user/**").hasRole("user")
		        .antMatchers("/hr/**").hasRole("hr")
		        .antMatchers("/admin/**").hasAnyRole("admin","sadmin")
		        .antMatchers("/sadmin/**").hasAnyRole("sadmin")
		        .anyRequest().authenticated()
		    .and()
		    //.formLogin().successForwardUrl("/user/d")
		    	.formLogin().loginPage("/")
		    	.loginProcessingUrl("/authentication/form")
		    	.successHandler(successHandler)
		    .and()
		    	.logout()
		    	.logoutSuccessUrl("/").logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                        HttpSession session = request.getSession();
                        String path = request.getContextPath() ;
                        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
                        session.setAttribute("islogin", false);
                        session.setAttribute("id", "");
                        System.out.println(session.getAttribute("islogin"));
                        response.sendRedirect("http://localhost:8082/");
                    }
                }).permitAll()
		    .and()
	    		.rememberMe()
	    		.rememberMeCookieName("remember")
	    		.rememberMeParameter("rememberMe")
	    		.tokenValiditySeconds(7*24*60*60);

	//	web.ignoring().antMatchers("/static/css/**","/static/js/**","/static/img/**");
		//web.ignoring().antMatchers("/usert/**");
	}
	
	
	
	@Bean
	public BCryptPasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	} 
}
